﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Xml;

namespace Lib_general
{
    public class Exec_Database
    {
        private SqlCommand cmd;
        private SqlDataAdapter adap;
        private DataSet ds = null;
        private string s_host = "", s_sa = "", s_pass = "", s_data = "", s_con = "";
        private SqlConnection con;

        public Exec_Database()
        {
            s_host = System("host");
            s_sa = System("sa");
            s_pass = System("pass");
            s_data = System("database");

            s_con = "Data Source=" + s_host + ";Initial Catalog=" + s_data + ";User ID=" + s_sa + ";Password=" + s_pass + "";
        }
        public void open_connection()
        {
            con = new SqlConnection(s_con);
            if (con.State == ConnectionState.Open) con.Close();
            con.Open();
        }
        public void close_connection()
        {
            con = new SqlConnection(s_con);
            if (con.State == ConnectionState.Open) con.Close();
            con.Dispose();
        }
        public string s_connect
        {
            get { return s_con; }
        }
        private string System(string sql)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load("..\\..\\..\\xml\\system.xml");
                XmlNodeList nodeLst = doc.GetElementsByTagName(sql);
                return nodeLst.Item(0).InnerText;
            }
            catch { return ""; }
        }
        public DataSet Get_data(string sql)
        {
            ds = new DataSet();
            try
            {
                con = new SqlConnection(s_con);
                if (con.State == ConnectionState.Open) con.Close();
                con.Open();
                cmd = new SqlCommand(sql, con);
                cmd.CommandType = CommandType.Text;
                adap = new SqlDataAdapter(cmd);
                adap.Fill(ds);
            }
            catch { }
            finally
            {
                cmd.Dispose(); con.Close(); con.Dispose();
            }
            return ds;
        }
        public bool Exec_data(string sql)
        {
            try
            {
                con = new SqlConnection(s_con);
                if (con.State == ConnectionState.Open) con.Close();
                con.Open();
                cmd = new SqlCommand(sql, con);
                cmd.CommandType = CommandType.Text;
                cmd.ExecuteNonQuery();
                return true;
            }
            catch { return false; }
            finally
            {
                cmd.Dispose(); con.Close(); con.Dispose();
            }
        }

    }
}
